//
//  TileGroupList.m
//  MapEdit
//
//  Created by Steven Canfield on 16/06/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "TileGroupList.h"


@implementation TileGroupList
- (id)initWithData:(NSData *)data {
	if( (self = [super init]) ) {
		int dataIndex  = 0;
		int groupIndex = 0;
		_groups = malloc( sizeof( tile_group_t * ) * [data length] / 52 );
		while( dataIndex < [data length] ) {
			dataIndex += 20; // Skipping 20 Bytes
			tile_group_t * group = malloc( sizeof( tile_group_t ) );
			int groupItemIndex = 0;
			for( groupItemIndex = 0; groupItemIndex < 16; groupItemIndex++ ) {
				u_int16_t groupItem;
				[data getBytes:&groupItem range:NSMakeRange( dataIndex, sizeof( u_int16_t ))];
				groupItem = NSSwapLittleShortToHost( groupItem );
				(*group).map[ groupItemIndex ] = groupItem;
				dataIndex += sizeof( u_int16_t );
			}
			_groups[ groupIndex ] = group;
			groupIndex++;
		}
		_groupCount = groupIndex;
		DebugLog(@"Loaded %i Groups", _groupCount );
	}
	return self;
}

- (int)indexForGroup:(int)group member:(int)member {
	if( group < 0 || group >= _groupCount ) {
		DebugLog(@"Group Index (%i) Out of Bounds (%i)", index, _groupCount);
	}
	if( member < 0 || member >= 16 ) {
		DebugLog(@"Member Index (%i) Out of Bounds (%i)", member, 16 );
	}
	return (*_groups[ group ]).map[ member ];
}

- (void)dealloc {
	free( _groups );
	[super dealloc];
}
@end
